package com.bw.lib_common.base

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.R
import com.bw.lib_common.base.state.RequestEvent
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author ytx
 * @date 2025-09-17 14:58
 * @description
 */
abstract class BaseActivity<VM:BaseViewModel,VDB:ViewDataBinding>:AppCompatActivity() {
    abstract val GlideApp: Any
    open val mPageCanBack:Boolean = true //不是第一次
    abstract val mLayoutResId:Int //布局id
    protected lateinit var mBinding:VDB //dataBinding
    protected lateinit var mRootView:ViewGroup //当前activity的根布局
    private var mLoadingView:View? = null //加载中视图
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //搞布局
        mBinding = DataBindingUtil.setContentView(this,mLayoutResId)
        mBinding.lifecycleOwner = this //生命周期绑定

        ARouter.getInstance().inject(this)
        //全局加载状态
        initGlobalView()
        //统一初始化
        initStatusBar()
        initView()
        initListener()
        initData()

    }

    /**
     * 全局加载状态
     */
    private fun initGlobalView() {
        mRootView = window.decorView as ViewGroup
        initLoadingView()
    }
    private fun initLoadingView(){
        if (mLoadingView == null){
            mLoadingView = layoutInflater.inflate(R.layout.dialog_common_progress,mRootView,false)
            mLoadingView!!.setOnClickListener {  }
            setLoadingViewVisible(false)
            mRootView.addView(mLoadingView)
        }
    }

    /**
     * 设置显示隐藏
     */
    fun setLoadingViewVisible(show:Boolean,msg:String = ""){
        mLoadingView?.let {
            val textView = it.findViewById<TextView>(R.id.tv_text)
            if (show && msg.isNotEmpty()){
                textView.text = msg
            }
            if (show){
                it.visibility = View.VISIBLE
            }else{
                it.visibility = View.GONE
            }
        }
    }

    /**
     * 添加公共状态监听
     */
    fun addCommonStateListener(flow:StateFlow<RequestEvent>){
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                flow.collectLatest{
                    when(it){
                        is RequestEvent.Loading -> {
                            setLoadingViewVisible(true)
                        }
                        is RequestEvent.Success -> {
                            setLoadingViewVisible(false)
                        }
                        is RequestEvent.Error -> {
                            setLoadingViewVisible(false)
                            onLoadFailed(it.msg)
                        }
                        is RequestEvent.Empty -> {
                            setLoadingViewVisible(false)
                            onEmpty()
                        }
                        is RequestEvent.Init -> {
                        }
                    }


                }
            }
        }
    }
    open fun onEmpty() {
        //子类可以处理空数据
    }
    open fun onLoadFailed(msg:String) {
        //子类可以处理失败
    }

    open fun showToast(stringRes: String) {
        Snackbar.make(window.decorView, stringRes, Snackbar.LENGTH_LONG).show()
    }

    open fun showToast(view: View?, stringRes: Int) {
        Snackbar.make(view ?: window.decorView, stringRes, Snackbar.LENGTH_LONG).show()
    }
    /**
     * 隐藏键盘
     */
    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    fun hideKeyboard(view: View) {
        (view.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?)?.hideSoftInputFromWindow(view.windowToken, 0)
    }
    /**
     * 显示键盘
     */
    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    fun showSoftKeyBoard(view: View) {
        view.requestFocus()
        view.postDelayed({
            val imm = view.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
        }, 200)

    }

    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    fun dismissKeyboard() {
        try {
            val view = window.peekDecorView()
            if (view != null) {
                val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                im.hideSoftInputFromWindow(view.windowToken, 0)
            }
        } catch (e: Exception) {
        }
    }

    open fun initStatusBar() {

    }
    open fun initView() {

    }
    open fun initListener() {

    }
    open fun initData() {

    }
    private var lastPressBack = 0L //记录上一次按下返回键的时间
    /**
     * 当前activity是不是最后一个activity
     *  不是：默认的
     *  是:是不是连续点击了2次，不超过2淼
     *      是：默认的
     *      不是：不退出引用，吐司再点一次退出app
     *
     */
    override fun onBackPressed() {
        //        super.onBackPressed()
        val timeStamp = System.currentTimeMillis()
        if (mPageCanBack){ //不是首页
            super.onBackPressed()
            return
        }
        //是首页
        if(isPressBackToExitApp(timeStamp)){
            super.onBackPressed()
            return
        }
    }

    fun isPressBackToExitApp(timeStamp:Long):Boolean{
        if(timeStamp == lastPressBack){
            return false
        }
        //小于2s
        if (timeStamp - lastPressBack < 2000){
            return true
        }else{
            showToast("再按一次退出app")
            lastPressBack = timeStamp
            return false
        }

    }
}